package com.ruoyi.web.controller.buy;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.buy.domain.entity.PO.BuyMaterialBillItemPO;
import com.ruoyi.buy.domain.entity.PO.BuyMaterialBillPO;
import com.ruoyi.buy.domain.entity.PO.BuyMaterialOtherItem;
import com.ruoyi.buy.domain.entity.PO.BuySpaPricePO;
import com.ruoyi.buy.domain.entity.buy0002.Buy0002SaveVO;
import com.ruoyi.buy.domain.entity.buy0002.Buy0003SpaImportDataNew;
import com.ruoyi.buy.domain.entity.importPO.BuyMaterialBillItemImport;
import com.ruoyi.buy.service.IBuy0001Service;
import com.ruoyi.buy.service.IBuy0002Service;
import com.ruoyi.buy.service.IBuyMaterialOtherItemService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysLogininfor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


/**
 * 角色信息
 * 
 * @author ruoyi
 */
@RestController
@Transactional(rollbackFor = Exception.class)
@RequestMapping("/buy/buy0002")
public class buy0002Controller extends BaseController {
    @Autowired
    private IBuy0002Service buy0002Service;

    @Autowired
    private IBuy0001Service buy0001Service;

    @Autowired
    private IBuyMaterialOtherItemService buyMaterialOtherItemService;

    @Autowired
    private RedisCache redisCache;

    @GetMapping("/list")
    public TableDataInfo list(BuyMaterialBillPO para) {
        startPage();
        List<BuyMaterialBillPO> list = buy0002Service.selectMaterialBillList(para);
        return getDataTable(list);
    }

    /**
     *
     */
    @PostMapping(value = "/save")
    public AjaxResult save(@RequestBody Buy0002SaveVO param) throws Exception {
        param.setCreateBy(getUsername());
        return success(buy0002Service.save(param));
    }

    /**
     *
     */
    @PostMapping(value = "/view")
    public AjaxResult view(@RequestBody BuyMaterialBillPO param) throws Exception {
        return success(buy0002Service.view(param));
    }

    @PostMapping(value = "/export")
    public String exprot(@RequestBody SysLogininfor logininfor) throws Exception {
        Workbook workBook = null;
        String folderPath ="";
        try {
            List<Buy0003SpaImportDataNew> data = JSONArray.parseArray(logininfor.getUserName(), Buy0003SpaImportDataNew.class);
            List<Buy0003SpaImportDataNew> result = data.stream().filter(x -> x.getnPrice() == null || x.getnPrice().compareTo(BigDecimal.ZERO) == 0).collect(Collectors.toList());
            if (result.size() == 0){
                throw new Exception("不存在需要询价的数据");
            }
//        ExcelUtil<Buy0003SpaImportData> util = new ExcelUtil<Buy0003SpaImportData>(Buy0003SpaImportData.class);
//        util.exportExcel(response, result, "询价单");
            //创建一个文件夹
            folderPath = "D:/myFolder/bill/" + System.currentTimeMillis();
            File dir = new File(folderPath);
            dir.mkdirs();
            Map<String,List<Buy0003SpaImportDataNew>> listByBrand = new HashMap<>();
//                    result.stream().collect(Collectors.groupingBy(Buy0003SpaImportDataNew::getVSelectBrand));
            //品牌分组
            List<String> brandList = new ArrayList<>();
            for (Buy0003SpaImportDataNew item:result
                 ) {
                String vKind = StringUtils.isEmpty(item.getvKind())?"" :item.getvKind();
                String selectBrand = StringUtils.isEmpty(item.getVSelectBrand())?"" :item.getVSelectBrand();
                if (vKind.equals("01")){
                    brandList.add("机加" + "-" + selectBrand);
                }else if (vKind.equals("02")){
                    brandList.add("外购" + "-" + selectBrand);
                }else{
                    brandList.add(vKind + "-" + selectBrand);
                }
            }
            brandList = brandList.stream().distinct().collect(Collectors.toList());

            for (String item :brandList
                 ) {
                List<Buy0003SpaImportDataNew>  buy0003SpaImportDataNewList = new ArrayList<>();
                for (Buy0003SpaImportDataNew item1:result
                ) {
                    String vKind = StringUtils.isEmpty(item1.getvKind())?"" :item1.getvKind();
                    String selectBrand = StringUtils.isEmpty(item1.getVSelectBrand())?"" :item1.getVSelectBrand();
                    String flag = "";
                    if (vKind.equals("01")){
                        flag = "机加" + "-" + selectBrand;
                    }else if (vKind.equals("02")){
                        flag = "外购" + "-" + selectBrand;
                    }else{
                        flag = vKind + "-" + selectBrand;
                    }
                    if (flag.equals(item)){
                        buy0003SpaImportDataNewList.add(item1);
                    }
                }
                listByBrand.put(item,buy0003SpaImportDataNewList);
            }

            for (String key:listByBrand.keySet()){

                // 设置Excel的标题等参数
                ExportParams exportParams = new ExportParams();
                exportParams.setSheetName(key);
                workBook = ExcelExportUtil.exportExcel(exportParams,Buy0003SpaImportDataNew.class,listByBrand.get(key));
                // 文件输出路径
                File file = new File(folderPath+"/"+key.replaceAll("\\s*","")+".xlsx");
                try (FileOutputStream fos = new FileOutputStream(file)) {
                    workBook.write(fos); // 将Excel写入文件
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(workBook != null) {
                try {
                    workBook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        long timestamp = System.currentTimeMillis();
        redisCache.setCacheObject("bill"+timestamp,folderPath,30, TimeUnit.SECONDS);
        return "bill"+timestamp;
    }

    @GetMapping ("/export/{folderFlag}")
    public void export(HttpServletResponse response, @PathVariable("folderFlag") String folderFlag) throws Exception
    {
        String folderPath = redisCache.getCacheObject(folderFlag);
        this.getZip(response,folderPath);
        File file = new File(folderPath);
        this.deleteFolder(file);
    }

    public void deleteFolder(File folder) {
        if(folder.isDirectory()) {
            File[] files = folder.listFiles();
            if(files != null) { // 如果文件夹为空，files可能为null
                for(File file : files) {
                    deleteFolder(file); // 递归删除子文件夹和文件
                }
            }
        }
        folder.delete(); // 删除空文件夹或者文件
    }

    public static void bord(Row row, XSSFCellStyle cellStyle, int j){
        for (int i = 0;i<=j;i++) {
            Cell cell = row.getCell(i);
            cell.setCellStyle(cellStyle);
        }
    }

    @PostMapping(value = "/selectSpaPriceByCondition")
    public AjaxResult selectSpaByCondition(@RequestBody BuySpaPricePO param) throws Exception {
        return success(buy0001Service.selectSpaByCondition(param));
    }


    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<BuyMaterialBillItemImport> util = new ExcelUtil<>(BuyMaterialBillItemImport.class);
        util.importTemplateExcel(response, "采购合同明细数据");
    }

    @PostMapping("/importData")
    public AjaxResult importData(List<MultipartFile> files,String updateSupport,String folderPath) throws Exception
    {
       return success(this.buy0002Service.importData(files,updateSupport,folderPath));
    }

    @GetMapping ("/exportData/{id}")
    public void exportData(HttpServletResponse response, @PathVariable("id") Long id) throws Exception
    {
        String filePath = this.buy0002Service.exportData(id);
        this.getZip(response,filePath);
    }

    private void getZip(HttpServletResponse response,String filePath) throws Exception
    {
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        try {
            File zipFile = new File(filePath + "文件.zip");
            File sourceFile = new File(filePath);
            File[] sourceFiles = sourceFile.listFiles();
            fos = new FileOutputStream(zipFile);
            zos = new ZipOutputStream(new BufferedOutputStream(fos));
            byte[] bufs = new byte[1024 * 10];
            for (int i = 0; i < sourceFiles.length; i++) {
                //创建ZIP实体，并添加进压缩包
                ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
                zos.putNextEntry(zipEntry);
                //读取待压缩的文件并写进压缩包里
                fis = new FileInputStream(sourceFiles[i]);
                bis = new BufferedInputStream(fis, 1024 * 10);
                int read = 0;
                while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
                    zos.write(bufs, 0, read);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally{
            //关闭流
            try {
                if(null != bis) bis.close();
                if(null != zos) zos.close();
                File zipFile = new File(filePath + "文件.zip");
                byte[] buffer = new byte[1024];
                BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(zipFile));
                OutputStream outputStream = response.getOutputStream();
                int length;
                while ((length = bufferedInputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, length);
                }
                bufferedInputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }

    @PostMapping("/importDataXJD")
    public AjaxResult importDataXJD(List<MultipartFile> files,String updateSupport,String billID) throws Exception
    {
        ExcelUtil<Buy0003SpaImportDataNew> util = new ExcelUtil<Buy0003SpaImportDataNew>(Buy0003SpaImportDataNew.class);
        List<Buy0003SpaImportDataNew> totalList = new ArrayList<>();
        for (MultipartFile file:files
             ) {
            //根据file得到Workbook,主要是要根据这个对象获取,传过来的excel有几个sheet页
            Workbook hssfWorkbook = getWorkBook(file);
            int sheetNum = hssfWorkbook.getNumberOfSheets();
            for (int i = 0; i < sheetNum; i++) {
                List<Buy0003SpaImportDataNew> list = getExcelData(file,i);
                totalList.addAll(list);
            }
        }
        return success(buy0002Service.exportXJDData(totalList,getUsername(),billID));
//        return success(1);
    }

    @PostMapping("/getSuggests")
    public AjaxResult getSuggests(@RequestBody  BuyMaterialBillItemPO para) throws Exception
    {
        BuyMaterialOtherItem buyMaterialOtherItem = new BuyMaterialOtherItem();
        buyMaterialOtherItem.setnMainId(para.getiD());
        List<BuyMaterialOtherItem> list = buyMaterialOtherItemService.selectBuyMaterialOtherItemList(buyMaterialOtherItem);
        return success(list);
    }

    @PostMapping("/saveSuggestDialog")
    public AjaxResult saveSuggestDialog(@RequestBody  List<BuyMaterialOtherItem> para) throws Exception
    {
        return success(this.buyMaterialOtherItemService.saveSuggestDialog(para));
    }

    @PostMapping("/deleteSuggestDialog")
    public AjaxResult deleteSuggestDialog(@RequestBody  BuyMaterialOtherItem para) throws Exception
    {
        return toAjax(this.buyMaterialOtherItemService.deleteBuyMaterialOtherItemById(para.getId()));
    }

    private List<Buy0003SpaImportDataNew> getExcelData(MultipartFile file,int i) throws Exception {
        ImportParams importParams = new ImportParams();
        // 表格标题行数，默认0
        importParams.setTitleRows(0);
        // 表头行数，默认1
        importParams.setHeadRows(1);
        // 开始读取的sheet位置，默认为0
        importParams.setStartSheetIndex(i);

        InputStream inputStream = file.getInputStream();
        return ExcelImportUtil.importExcel(inputStream, Buy0003SpaImportDataNew.class, importParams);
    }

    private Workbook getWorkBook(MultipartFile file) throws IOException {
        //这样写excel能兼容03和07
        InputStream is = file.getInputStream();
        Workbook hssfWorkbook = null;
        try {
            hssfWorkbook = new HSSFWorkbook(is);
        } catch (Exception ex) {
            is =file.getInputStream();
            hssfWorkbook = new XSSFWorkbook(is);
        }
        return hssfWorkbook;
    }




}
